import { NextApiResponse } from '@/libs/apiResponse';
import { NextResponse, type NextRequest } from 'next/server';
import { ChatClient } from 'dify-client';
import { getDifyConfig, type DifyServices } from '@/config/dify';

export interface DifyRequestBody<T = Record<string, unknown>> {
  query: string;
  inputs?: {
    service: DifyServices;
  } & T;
  response_mode?: string;
  user?: string;
  conversation_id?: string;
  files?: File[];
  auto_generate_name?: boolean;
}

export async function POST(request: NextRequest) {
  try {
    console.log('POST request received');
    const body: Partial<DifyRequestBody<any>> = await request.json();
    console.log(body.inputs?.service);

    if (!body.inputs?.service) {
      throw new Error('请传递 Dify 服务参数');
    }

    const service = getDifyConfig(body.inputs?.service);

    const user = body.user || 'random';
    const query = body.query || 'Please tell me a short story';
    const inputs = body.inputs || {};

    const conversation_id = body.conversation_id;
    const completionClient = new ChatClient(service.apiKey, service.baseUrl);
    const response = await completionClient.createChatMessage(
      inputs,
      query,
      user,
      true, // stream mode
      conversation_id
    );

    return new Response(response.data as ReadableStream, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        Connection: 'keep-alive',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        'X-Accel-Buffering': 'no', // 禁用nginx缓冲
      },
      status: 200,
    });
  } catch (error) {
    console.error('API Error:', error);

    return NextApiResponse.serverError('服务器内部错误');
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    {},
    {
      status: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      },
    }
  );
}
